﻿using System;
using System.Collections.Generic;
using System.Text;
using Blazing.BusinessObjects.Cms;
using System.Web.Configuration;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.IO;
using Blazing.BusinessObjects.Widgets;

namespace Blazing.Web.Util
{
    /// <summary>
    /// A common class used to format urls
    /// </summary>
    public class UrlFormatter
    {
        public static bool IsUsingISAPI
        {
            get
            {
                bool useIsapi = true;
                string raw = WebConfigurationManager.AppSettings["UseISAPI"];
                if(!string.IsNullOrEmpty(raw))
                {
                    useIsapi = bool.Parse(raw);
                }
                return useIsapi;
            }
        }

        public static string FormatUrl(object pageId)
        {
            int pageid = Convert.ToInt32(pageId);
            Contentpage page = CmsFacade.GetPageById(pageid);
            return FormatUrl(page);
        }

        public static string FormatUrl(Contentpage page)
        {
            return FormatUrl(page.Url);
        }

        public static string FormatUrl(string url)
        {
            string itemUrl = url;
            if (!IsUsingISAPI && url.Length > 1 && url.EndsWith("/"))
                itemUrl = url.Substring(0, url.Length - 1) + ".aspx";
            return itemUrl;
        }

        /// <summary>
        /// Formats CMS page ids to point to the correct urls
        /// Accepts: [page:4 About us] or [page.href:4]
        /// </summary>
        public static string FormatUrlsInText(string data)
        {
            MatchEvaluator matchEval = delegate(Match m)
            {
                string command = m.Result("$1");
                object pageid = m.Result("$2");
                string description = m.Result("$3");
                string retval = "";

                if(command.Equals("page"))
                {
                    retval = string.Format("<a href=\"{0}\">{1}</a>", FormatUrl((object)pageid), description);
                }
                else if(command.Equals("page.href"))
                {
                    retval = FormatUrl((object)pageid);
                }

                return string.IsNullOrEmpty(retval) ? m.ToString() : retval;
            };
            return Regex.Replace(data, @"\[([a-z,\.]+):([0-9]{1,3})\ ?([\w,\ \']*)\]", matchEval);
        }

        public static string FormatWidgetsInText(string data, Page parentPage, Control namingContainer)
        {
            MatchEvaluator matchEval = delegate(Match m)
            {
                string command = m.Result("$1");
                string path = m.Result("$2");
                string parameters = m.Result("$3");
                string retval = "";
                Control control = null;

                if (command.Equals("widget.href"))
                {
                    control = parentPage.LoadControl(path);
                    
                }
                else if (command.Equals("widget"))
                {
                    Widget w = Widget.Load(int.Parse(path));
                    if(w != null)
                        control = parentPage.LoadControl(w.Path);
                }

                if (!string.IsNullOrEmpty(parameters) && control != null)
                {
                    parameters = parameters.TrimStart(':');
                    WidgetParameters.SetParameters(control, parameters);
                }

                if (control != null)
                {
                    MemoryStream memStream = new MemoryStream();
                    try
                    {
                        namingContainer.Controls.Add(control);
                        HtmlTextWriter wt = new HtmlTextWriter(new StreamWriter(memStream));
                        control.Page = parentPage;
                        control.RenderControl(wt);
                        wt.Flush();
                        memStream.Seek(0, 0);
                        StreamReader rd = new StreamReader(memStream);
                        retval = rd.ReadToEnd();
                        namingContainer.Controls.Remove(control);
                    }
                    finally
                    {
                        memStream.Dispose();
                    }
                }

                return string.IsNullOrEmpty(retval) ? m.ToString() : retval;
            };
            return Regex.Replace(data, @"\[([a-z,\.]+):([\w,\~,\/,\.]*)(:[\w\=\;]*)?\]", matchEval);
            //\[([a-z,\.]+):([A-Z,a-z,0-9,\~,\/,\.]*)\]
        }
    }
}
